﻿using ConnectDatabase;
using Database;
using DevExpress.Web.ASPxEditors;
using Galileo;
using IBE;
using IBE.GalileoLccService;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace Web
{
    public partial class Book : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitData();
            }
        }

        protected FareData GetFareData()
        {
            FareData fareData = null;
            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["SelectedValue"]) && !string.IsNullOrEmpty(Request.QueryString["Search"]))
                {
                    if (Session[Request.QueryString["Search"] + Request.QueryString["SelectedValue"]] != null)
                    {
                        fareData = (FareData)Session[Request.QueryString["Search"] + Request.QueryString["SelectedValue"]];
                    }
                    else
                    {
                        Response.Redirect("~/Error.aspx", false);
                    }
                }
                else
                {
                    Response.Redirect("~/Error.aspx", false);
                }
            }
            catch
            {
                Response.Redirect("~/Error.aspx", false);
            }

            return fareData;
        }

        protected Flight GetDepartureFlight(FareData fareData)
        {
            Flight flight = null;
            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["SelectedValue"]) && !string.IsNullOrEmpty(Request.QueryString["Search"]))
                {
                    if (Session[Request.QueryString["Search"] + Request.QueryString["SelectedValue"] + "DepartureId"] != null)
                    {
                        int DepartureId = Convert.ToInt32(Session[Request.QueryString["Search"] + Request.QueryString["SelectedValue"] + "DepartureId"]);
                        flight = fareData.ListDepartureFlight[DepartureId];
                    }
                    else
                    {
                        Response.Redirect("~/Error.aspx", false);
                    }
                }
                else
                {
                    Response.Redirect("~/Error.aspx", false);
                }
            }
            catch
            {
                Response.Redirect("~/Error.aspx", false);
            }

            return flight;
        }

        protected Flight GetReturnFlight(FareData fareData)
        {
            if (fareData.HasReturn)
            {
                Flight flight = null;
                try
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["SelectedValue"]))
                    {
                        if (Session[Request.QueryString["Search"] + Request.QueryString["SelectedValue"] + "ReturnId"] != null)
                        {
                            int ReturnId = Convert.ToInt32(Session[Request.QueryString["Search"] + Request.QueryString["SelectedValue"] + "ReturnId"]);
                            flight = fareData.ListReturnFlight[ReturnId];
                        }
                        else
                        {
                            Response.Redirect("~/Error.aspx", false);
                        }
                    }
                    else
                    {
                        Response.Redirect("~/Error.aspx", false);
                    }
                }
                catch
                {
                    Response.Redirect("~/Error.aspx", false);
                }

                return flight;
            }
            else
            {
                return null;
            }
        }

        protected void FillPriceAndFee(FareData fareData)
        {
            //Fare
            lblTotalAdt.Text = fareData.TotalAdult.ToString();
            lblFareAdt.Text = ((fareData.FareAdult + fareData.FeeChild) * fareData.TotalAdult).ToString("#,0.##") + " " + fareData.CurrencyCode;

            if (fareData.TotalChild > 0)
            {
                FareChd.Visible = true;
                lblTotalChd.Text = fareData.TotalChild.ToString();
                lblFareChd.Text = ((fareData.FareChild + fareData.FeeChild) * fareData.TotalChild).ToString("#,0.##") + " " + fareData.CurrencyCode;
            }

            if (fareData.TotalInfant > 0)
            {
                FareInf.Visible = true;
                lblTotalInf.Text = fareData.TotalInfant.ToString();
                lblFareInf.Text = ((fareData.FareInfant + fareData.FeeInfant) * fareData.TotalInfant).ToString("#,0.##") + " " + fareData.CurrencyCode;
            }

            lblGrandTotal.Text = (fareData.TotalFare + fareData.TotalFee).ToString("#,0.##") + " " + fareData.CurrencyCode;
        }

        protected void InitData()
        {
            try
            {
                FareData fareData = GetFareData();
                if (fareData != null)
                {
                    //Detail flight
                    Flight departFlt = GetDepartureFlight(fareData);
                    Flight returnFlt = GetReturnFlight(fareData);
                    repDepartureFlightDetail.DataSource = departFlt.ListAvailFlt;
                    repDepartureFlightDetail.DataBind();
                    if (returnFlt != null)
                    {
                        repReturnFlightDetail.DataSource = returnFlt.ListAvailFlt;
                        repReturnFlightDetail.DataBind();
                        pnReturn.Visible = true;
                    }

                    //Price
                    FillPriceAndFee(fareData);

                    //Pax
                    int PaxNum = 0;
                    List<Pax> listAdult = new List<Pax>();
                    for (int i = 0; i < fareData.TotalAdult; i++)
                    {
                        PaxNum++;
                        Pax pax = new Pax();
                        pax.Id = PaxNum;
                        listAdult.Add(pax);
                    }
                    repPaxAdult.DataSource = listAdult;
                    repPaxAdult.DataBind();

                    List<Pax> listChild = new List<Pax>();
                    for (int i = 0; i < fareData.TotalChild; i++)
                    {
                        PaxNum++;
                        Pax pax = new Pax();
                        pax.Id = PaxNum;
                        if (!fareData.HasReturn)
                        {
                            pax.MinDateAge = fareData.DepartureDate.AddYears(-12);
                            pax.MaxDateAge = fareData.DepartureDate.AddYears(-2);
                        }
                        else
                        {
                            pax.MinDateAge = fareData.ReturnDate.AddYears(-12);
                            pax.MaxDateAge = fareData.ReturnDate.AddYears(-2);
                        }
                        listChild.Add(pax);
                    }
                    repPaxChild.DataSource = listChild;
                    repPaxChild.DataBind();

                    List<Pax> listInfant = new List<Pax>();
                    for (int i = 0; i < fareData.TotalInfant; i++)
                    {
                        PaxNum++;
                        Pax pax = new Pax();
                        pax.Id = PaxNum;
                        if (!fareData.HasReturn)
                        {
                            pax.MinDateAge = fareData.DepartureDate.AddYears(-2);
                            pax.MaxDateAge = fareData.DepartureDate;
                        }
                        else
                        {
                            pax.MinDateAge = fareData.ReturnDate.AddYears(-2);
                            pax.MaxDateAge = fareData.ReturnDate;
                        }
                        listInfant.Add(pax);
                    }
                    repPaxInfant.DataSource = listInfant;
                    repPaxInfant.DataBind();
                }
                else
                {
                    Response.Redirect("~/Error.aspx", false);
                }
            }
            catch
            {
                Response.Redirect("~/Error.aspx", false);
            }
        }

        protected bool CheckValidInput()
        {
            bool isOk = true;
            #region Adult
            foreach (RepeaterItem item in repPaxAdult.Items)
            {
                //RadDatePicker calBirthday = (RadDatePicker)item.FindControl("calBirthday");
                //if (calBirthday != null)
                //{

                //}
            }
            #endregion

            #region Children
            foreach (RepeaterItem item in repPaxChild.Items)
            {
                //RadDatePicker calBirthday = (RadDatePicker)item.FindControl("calBirthday");
                //if (calBirthday != null)
                //{
                //    int age = DateTime.Now.Year - calBirthday.SelectedDate.Value.Year;
                //    if (age > 12)
                //    {
                //        return false;
                //    }
                //}
            }
            #endregion

            #region Infant
            foreach (RepeaterItem item in repPaxInfant.Items)
            {
                //RadDatePicker calBirthday = (RadDatePicker)item.FindControl("calBirthday");
                //if (calBirthday != null)
                //{
                //    int age = DateTime.Now.Year - calBirthday.SelectedDate.Value.Year;
                //    if (age > 2)
                //    {
                //        return false;
                //    }
                //}
            }
            #endregion
            return isOk;
        }

        protected PNRBFPrimaryBldChgMods GetPNRBFPrimaryBldChgMods(FareData fareData)
        {
            PNRBFPrimaryBldChgMods pNRBFPrimaryBldChgMods = new PNRBFPrimaryBldChgMods();
            pNRBFPrimaryBldChgMods.ItemAry = new List<PNRBFPrimaryBldChgMods.Item>();
            int paxCount = 0;

            #region Adult
            foreach (RepeaterItem item in repPaxAdult.Items)
            {
                paxCount++;
                PNRBFPrimaryBldChgMods.Item obj = new PNRBFPrimaryBldChgMods.Item();

                obj.DataBlkInd = "N";
                obj.EditTypeInd = "A";
                obj.LNameID = paxCount.ToString("00");
                obj.FNameItem.PsgrNum = "01";
                obj.FNameItem.AbsNameNum = paxCount.ToString("00");

                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                if (ddlTitle != null)
                {

                }

                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                if (txtLastName != null)
                {
                    obj.FNameItem.FName = Common.ConvertToUnSignString(txtLastName.Text.Trim()).ToUpper().Replace(" ", "");
                }

                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                if (txtFirstName != null)
                {
                    obj.LName = Common.ConvertToUnSignString(txtFirstName.Text.Trim()).ToUpper().Replace(" ", "");
                }

                pNRBFPrimaryBldChgMods.ItemAry.Add(obj);
            }
            #endregion

            #region Children
            foreach (RepeaterItem item in repPaxChild.Items)
            {
                paxCount++;
                PNRBFPrimaryBldChgMods.Item obj = new PNRBFPrimaryBldChgMods.Item();

                obj.DataBlkInd = "N";
                obj.EditTypeInd = "A";
                obj.LNameID = paxCount.ToString("00");
                obj.FNameItem.PsgrNum = "01";
                obj.FNameItem.AbsNameNum = paxCount.ToString("00");

                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                if (ddlTitle != null)
                {

                }

                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                if (txtLastName != null)
                {
                    obj.FNameItem.FName = Common.ConvertToUnSignString(txtLastName.Text.Trim()).ToUpper().Replace(" ", "");
                }

                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                if (txtFirstName != null)
                {
                    obj.LName = Common.ConvertToUnSignString(txtFirstName.Text.Trim()).ToUpper().Replace(" ", "");
                }

                ASPxDateEdit dateBirthday = (ASPxDateEdit)item.FindControl("dateBirthday");
                if (dateBirthday != null)
                {
                    int age = DateTime.Now.Year - dateBirthday.Date.Year;
                    obj.FNameItem.FNameRmk = "P-C" + age.ToString("00");
                }

                pNRBFPrimaryBldChgMods.ItemAry.Add(obj);
            }
            #endregion

            #region Infant
            foreach (RepeaterItem item in repPaxInfant.Items)
            {
                paxCount++;
                PNRBFPrimaryBldChgMods.Item obj = new PNRBFPrimaryBldChgMods.Item();

                obj.DataBlkInd = "N";
                obj.EditTypeInd = "A";
                obj.NameType = "I";
                obj.LNameID = paxCount.ToString("00");
                obj.FNameItem.PsgrNum = "01";
                obj.FNameItem.AbsNameNum = paxCount.ToString("00");

                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                if (ddlTitle != null)
                {

                }

                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                if (txtLastName != null)
                {
                    obj.FNameItem.FName = Common.ConvertToUnSignString(txtLastName.Text.Trim()).ToUpper().Replace(" ", "");
                }

                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                if (txtFirstName != null)
                {
                    obj.LName = Common.ConvertToUnSignString(txtFirstName.Text.Trim()).ToUpper().Replace(" ", "");
                }

                if (fareData.HasChangedClass)
                {
                    obj.FNameItem.FNameRmk = "P-C11";
                }
                else
                {
                    ASPxDateEdit dateBirthday = (ASPxDateEdit)item.FindControl("dateBirthday");
                    if (dateBirthday != null)
                    {
                        obj.FNameItem.FNameRmk = Common.ConvertEnglishDateTime(dateBirthday.Date);
                    }
                }

                pNRBFPrimaryBldChgMods.ItemAry.Add(obj);
            }
            #endregion

            //PhoneQual
            Flight departureFlgt = GetDepartureFlight(fareData);
            if (departureFlgt.StartPointCity.Code == "SGN")
            {
                pNRBFPrimaryBldChgMods.City = "SGN";
            }
            else
            {
                pNRBFPrimaryBldChgMods.City = "HAN";
            }
            pNRBFPrimaryBldChgMods.Type = "B";
            pNRBFPrimaryBldChgMods.PhoneNumber = txtPhoneNumber.Text.Trim();

            //TkQual
            Common utility = new Common();
            DateTime lastTkDt = utility.GetDate(fareData.FareInfo.ListGenQuoteDetails[0].LastTkDt, "1200");
            foreach (GenQuoteDetails item in fareData.FareInfo.ListGenQuoteDetails)
            {
                if (lastTkDt > utility.GetDate(item.LastTkDt, "1200"))
                {
                    lastTkDt = utility.GetDate(item.LastTkDt, "1200");
                }
            }
            pNRBFPrimaryBldChgMods.Tk = "TAU/" + lastTkDt.ToString("ddMMM", new System.Globalization.CultureInfo("en-US")).ToUpper();

            return pNRBFPrimaryBldChgMods;
        }

        protected StorePriceMods GetStorePriceMods(FareData fareData)
        {
            StorePriceMods storePriceMods = new StorePriceMods();

            storePriceMods.PsgrAry1 = new List<StorePriceMods.Psgr>();
            storePriceMods.PsgrAry2 = new List<StorePriceMods.Psgr>();

            int paxCount = 0;
            foreach (RepeaterItem item in repPaxAdult.Items)
            {
                paxCount++;
                StorePriceMods.Psgr Psgr = new StorePriceMods.Psgr();
                Psgr.LNameNum = paxCount.ToString("00");
                Psgr.PsgrNum = paxCount.ToString("00");
                Psgr.AbsNameNum = paxCount.ToString("00");
                Psgr.PIC = "";
                storePriceMods.PsgrAry1.Add(Psgr);
                storePriceMods.PsgrAry2.Add(Psgr);
            }

            foreach (RepeaterItem item in repPaxChild.Items)
            {
                paxCount++;
                StorePriceMods.Psgr Psgr = new StorePriceMods.Psgr();
                Psgr.LNameNum = paxCount.ToString("00");
                Psgr.PsgrNum = paxCount.ToString("00");
                Psgr.AbsNameNum = paxCount.ToString("00");
                ASPxDateEdit dateBirthday = (ASPxDateEdit)item.FindControl("dateBirthday");
                if (dateBirthday != null)
                {
                    int age = DateTime.Now.Year - dateBirthday.Date.Year;
                    Psgr.PIC = "C" + age.ToString("00");
                }
                storePriceMods.PsgrAry1.Add(Psgr);
                storePriceMods.PsgrAry2.Add(Psgr);
            }

            foreach (RepeaterItem item in repPaxInfant.Items)
            {
                paxCount++;
                StorePriceMods.Psgr Psgr = new StorePriceMods.Psgr();
                Psgr.LNameNum = paxCount.ToString("00");
                Psgr.PsgrNum = paxCount.ToString("00");
                Psgr.AbsNameNum = paxCount.ToString("00");
                if (fareData.HasChangedClass)
                {
                    Psgr.PIC = "C11";
                }
                else
                {
                    Psgr.PIC = "INF";
                }
                storePriceMods.PsgrAry1.Add(Psgr);
                storePriceMods.PsgrAry2.Add(Psgr);
            }

            StorePriceMods.StructGenQuoteInfo GenQuoteInfo = new StorePriceMods.StructGenQuoteInfo();
            GenQuoteInfo.BkDtOverride = "N";
            GenQuoteInfo.EUROverride = "N";
            GenQuoteInfo.LCUOverride = "N";
            storePriceMods.GenQuoteInfo = GenQuoteInfo;

            StorePriceMods.StructSegSelection SegSelection = new StorePriceMods.StructSegSelection();
            SegSelection.SegRangeAry = new List<StorePriceMods.SegRange>();
            SegSelection.ReqAirVPFs = "Y";
            StorePriceMods.SegRange SegRange = new StorePriceMods.SegRange();
            SegRange.StartSeg = "00";
            SegRange.EndSeg = "00";
            SegRange.FareType = "P";
            SegRange.CRSInd = "1G";
            SegRange.PCC = "82P";
            SegRange.PublishedFaresInd = "Y";
            SegRange.Type = "A";
            SegSelection.SegRangeAry.Add(SegRange);
            storePriceMods.SegSelection = SegSelection;

            return storePriceMods;
        }

        protected AirSegSellMods GetAirSegSellMods(FareData fareData)
        {
            Common utility = new Common();
            AirSegSellMods airSegSellMods = new AirSegSellMods();
            airSegSellMods.ListAirSegSell = new List<AirSegSellMods.AirSegSell>();
            Flight departureFlgt = GetDepartureFlight(fareData);
            Flight returnFlgt = GetReturnFlight(fareData);

            int index = 0;
            foreach (AvailFlt obj in departureFlgt.ListAvailFlt)
            {
                AirSegSellMods.AirSegSell AirSegSell = new AirSegSellMods.AirSegSell();
                AirSegSell.Vnd = obj.AirV;
                AirSegSell.FltNum = Convert.ToInt32(obj.FltNum).ToString("0000");
                AirSegSell.Class = obj.ClassAdult;
                AirSegSell.StartDt = obj.StartDt;
                AirSegSell.StartAirp = obj.StartAirp;
                AirSegSell.EndAirp = obj.EndAirp;
                AirSegSell.Status = "NN";
                AirSegSell.NumPsgrs = (fareData.TotalAdult + fareData.TotalChild).ToString();
                DateTime startDt = utility.GetDate(obj.StartDt, obj.StartTm);
                DateTime endDt = utility.GetDate(obj.EndDt, obj.EndTm);
                AirSegSell.StartTm = startDt.ToString("hhMM");
                AirSegSell.EndTm = endDt.ToString("hhMM");

                TimeSpan DtChg = endDt - startDt;
                if (DtChg.Days == 0)
                {
                    AirSegSell.DtChg = "00";
                }
                else if (DtChg.Days == 1)
                {
                    AirSegSell.DtChg = "01";
                }
                else if (DtChg.Days == 2)
                {
                    AirSegSell.DtChg = "02";
                }
                else if (DtChg.Days == 3)
                {
                    AirSegSell.DtChg = "03";
                }

                AirSegSell.AvailDispType = "G";
                AirSegSell.AvailJrnyNum = "01";
                AirSegSell.NeutralFltLineNum = "00";

                airSegSellMods.ListAirSegSell.Add(AirSegSell);
                index++;
            }

            if (returnFlgt != null)
            {
                index = 0;
                foreach (AvailFlt obj in returnFlgt.ListAvailFlt)
                {
                    AirSegSellMods.AirSegSell AirSegSell = new AirSegSellMods.AirSegSell();
                    AirSegSell.Vnd = obj.AirV;
                    AirSegSell.FltNum = Convert.ToInt32(obj.FltNum).ToString("0000");
                    AirSegSell.Class = obj.ClassAdult;
                    AirSegSell.StartDt = obj.StartDt;
                    AirSegSell.StartAirp = obj.StartAirp;
                    AirSegSell.EndAirp = obj.EndAirp;
                    AirSegSell.Status = "NN";
                    AirSegSell.NumPsgrs = (fareData.TotalAdult + fareData.TotalChild).ToString();
                    DateTime startDt = utility.GetDate(obj.StartDt, obj.StartTm);
                    DateTime endDt = utility.GetDate(obj.EndDt, obj.EndTm);
                    AirSegSell.StartTm = startDt.ToString("hhMM");
                    AirSegSell.EndTm = endDt.ToString("hhMM");

                    TimeSpan DtChg = endDt - startDt;
                    if (DtChg.Days == 0)
                    {
                        AirSegSell.DtChg = "00";
                    }
                    else if (DtChg.Days == 1)
                    {
                        AirSegSell.DtChg = "01";
                    }
                    else if (DtChg.Days == 2)
                    {
                        AirSegSell.DtChg = "02";
                    }
                    else if (DtChg.Days == 3)
                    {
                        AirSegSell.DtChg = "03";
                    }

                    AirSegSell.AvailDispType = "G";
                    AirSegSell.AvailJrnyNum = "02";
                    AirSegSell.NeutralFltLineNum = "00";

                    airSegSellMods.ListAirSegSell.Add(AirSegSell);
                    index++;
                }
            }
            return airSegSellMods;
        }

        protected EndTransactionMods GetEndTransactionMods()
        {
            EndTransactionMods obj = new EndTransactionMods();
            obj.ETInd = "E";
            obj.RcvdFrom = "GALILEO";
            obj.SkipTEdits = "Y";
            return obj;
        }

        protected int SaveBooking(Flight departureFlight, Flight returnFlight, FareData fareData)
        {
            int id = 0;
            //Lưu booking vào database
            tblBooking booking = new tblBooking();
           
            booking.DepartureAirportCode = departureFlight.StartPointAirport.Code;
            booking.DestinationAirportCode = departureFlight.EndPointAirport.Code;
            booking.BookingStatus = "FAIL"; //Mặc định là Fail
            booking.ItineraryType = fareData.HasReturn;
            booking.AirlineCode = departureFlight.AirlineDetail.Code;
            booking.ValidatingCarrier = departureFlight.AirlineDetail.Code;
            booking.BookingDate = DateTime.Now;
            booking.BookingCode = "";
            booking.DepartureDate = fareData.DepartureDate;
            if (fareData.HasReturn)
            {
                booking.ReturnDate = fareData.ReturnDate;
            }
            booking.FullName = txtContactName.Text.Trim();
            booking.Email = txtEmail.Text.Trim();
            booking.Phone = txtPhoneNumber.Text.Trim();
            booking.ContactTitle = ddlContactTitle.SelectedIndex == 0 ? "Ông" : "Bà";
            booking.Address = txtContactAddress.Text.Trim();
            booking.PassengerNo = fareData.TotalPax;
            booking.TotalPrice = fareData.TotalFare;
            booking.TotalFee = fareData.TotalFee;
            booking.Discount = 0;
            booking.BSP = departureFlight.AirlineDetail.BSP != null ? departureFlight.AirlineDetail.BSP : false;
            booking.IBE = fareData.IBE == "galileo" ? "Galileo" : "Low cost";
            booking.TransitPoint = departureFlight.StopNum;
            if (fareData.HasReturn)
            {
                booking.TransitPoint += returnFlight.StopNum;
            }
            booking.Remark = txtNote.Text;
            booking.Visible = true;
            booking.LanguageCode = "vi-VN";
            booking.CurrencyCode = fareData.CurrencyCode;

            id = new BookingDB().Insert(booking);
            return id;
        }

        protected void SavePassengers(int bookingId, FareData fareData, HttpContext context)
        {
            tblPassenger pax;

            int paxCount = 0;
            foreach (RepeaterItem item in repPaxAdult.Items)
            {
                //Save Passenger
                pax = new tblPassenger();
                pax.BookingId = bookingId;
                pax.PassengerType = "ADT";
                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                
                if (txtFirstName != null && txtLastName != null && ddlTitle != null)
                {
                    pax.FirstName = txtFirstName.Text.Trim();
                    pax.LastName = txtLastName.Text.Trim();
                    pax.Gender = (ddlTitle.SelectedIndex == 0) ? true : false;
                }
                pax.Price = fareData.FareAdult;
                pax.Tax = 0;
                pax.Fee = fareData.FeeAdult;

                int paxId = new PassengerDB().Insert(pax);
                paxCount++;
            }

            paxCount = 0;
            foreach (RepeaterItem item in repPaxChild.Items)
            {
                //Save Passenger
                pax = new tblPassenger();
                pax.BookingId = bookingId;
                pax.PassengerType = "CHD";
                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                if (txtFirstName != null && txtLastName != null && ddlTitle != null)
                {
                    pax.FirstName = txtFirstName.Text.Trim();
                    pax.LastName = txtLastName.Text.Trim();
                    pax.Gender = (ddlTitle.SelectedIndex == 0) ? true : false;
                }
                pax.Price = fareData.FareChild;
                pax.Tax = 0;
                pax.Fee = fareData.FeeChild;
                ASPxDateEdit dateBirthday = (ASPxDateEdit)item.FindControl("dateBirthday");
                if (dateBirthday != null)
                {
                    pax.Birthday = dateBirthday.Date;
                }
                int paxId = new PassengerDB().Insert(pax);
                paxCount++;
            }

            paxCount = 0;
            foreach (RepeaterItem item in repPaxInfant.Items)
            {
                //Save Passenger
                pax = new tblPassenger();
                pax.BookingId = bookingId;
                pax.PassengerType = "INF";
                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                if (txtFirstName != null && txtLastName != null && ddlTitle != null)
                {
                    pax.FirstName = txtFirstName.Text.Trim();
                    pax.LastName = txtLastName.Text.Trim();
                    pax.Gender = (ddlTitle.SelectedIndex == 0) ? true : false;
                }
                pax.Price = fareData.FareInfant;
                pax.Tax = 0;
                pax.Fee = fareData.FeeInfant;
                ASPxDateEdit dateBirthday = (ASPxDateEdit)item.FindControl("dateBirthday");
                if (dateBirthday != null)
                {
                    pax.Birthday = dateBirthday.Date;
                }
                int paxId = new PassengerDB().Insert(pax);
                paxCount++;
            }
        }

        protected List<Passenger> GetListPaxForLcc()
        {
            List<Passenger> listPassengers = new List<Passenger>();

            #region Adult
            foreach (RepeaterItem item in repPaxAdult.Items)
            {
                Passenger pax = new Passenger();

                //Type
                pax.Type = "ADT";

                //FirstName
                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                pax.FirstName = Common.ConvertToUnSignString(txtFirstName.Text.Trim()).ToUpper().Replace(" ", "");

                //LastName
                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                pax.LastName = Common.ConvertToUnSignString(txtLastName.Text.Trim()).ToUpper().Replace(" ", "");

                //Gender
                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                pax.Gender = ddlTitle.SelectedIndex == 0 ? "1" : "0";

                //Birthday
                pax.Birthday = "12/03/1986";

                //Phone
                pax.Phone = txtPhoneNumber.Text;

                //Email
                //pax.Email = txtEmail.Text;
                pax.Email = "test@gmail.com";

                //PassportNumber
                pax.PassportNumber = "123456789";

                //PassportExpiryDate
                pax.PassportExpiryDate = "01/01/2020";

                //PassportIssueCountry
                pax.PassportIssueCountry = "VN";

                listPassengers.Add(pax);

            }
            #endregion

            #region Children
            foreach (RepeaterItem item in repPaxChild.Items)
            {
                Passenger pax = new Passenger();

                //Type
                pax.Type = "CHD";

                //FirstName
                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                pax.FirstName = Common.ConvertToUnSignString(txtFirstName.Text.Trim()).ToUpper().Replace(" ", "");

                //LastName
                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                pax.LastName = Common.ConvertToUnSignString(txtLastName.Text.Trim()).ToUpper().Replace(" ", "");

                //Gender
                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                pax.Gender = ddlTitle.SelectedIndex == 0 ? "1" : "0";

                //Birthday
                ASPxDateEdit dateBirthday = (ASPxDateEdit)item.FindControl("dateBirthday");
                pax.Birthday = dateBirthday.Date.ToString("dd/MM/yyyy");

                //PassportNumber
                pax.PassportNumber = "123456789";

                //PassportExpiryDate
                pax.PassportExpiryDate = "01/01/2020";

                //PassportIssueCountry
                pax.PassportIssueCountry = "VN";

                listPassengers.Add(pax);
            }
            #endregion

            #region Infant
            foreach (RepeaterItem item in repPaxInfant.Items)
            {
                Passenger pax = new Passenger();

                //Type
                pax.Type = "INF";

                //FirstName
                TextBox txtFirstName = (TextBox)item.FindControl("txtFirstName");
                pax.FirstName = Common.ConvertToUnSignString(txtFirstName.Text.Trim()).ToUpper().Replace(" ", "");

                //LastName
                TextBox txtLastName = (TextBox)item.FindControl("txtLastName");
                pax.LastName = Common.ConvertToUnSignString(txtLastName.Text.Trim()).ToUpper().Replace(" ", "");

                //Gender
                DropDownList ddlTitle = (DropDownList)item.FindControl("ddlTitle");
                pax.Gender = ddlTitle.SelectedIndex == 0 ? "1" : "0";

                //Birthday
                ASPxDateEdit dateBirthday = (ASPxDateEdit)item.FindControl("dateBirthday");
                pax.Birthday = dateBirthday.Date.ToString("dd/MM/yyyy");

                //PassportNumber
                pax.PassportNumber = "123456789";

                //PassportExpiryDate
                pax.PassportExpiryDate = "01/01/2020";

                //PassportIssueCountry
                pax.PassportIssueCountry = "VN";

                listPassengers.Add(pax);
            }
            #endregion

            return listPassengers;
        }

        protected void btnBook_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsValid)
                {
                    return;
                }
                if (CheckValidInput())
                {
                    if (ckbAccept.Checked)
                    {
                        FareData fareData = GetFareData();
                        Flight departureFlight = GetDepartureFlight(fareData);
                        Flight returnFlight = GetReturnFlight(fareData);
                        Common utility = new Common();

                        int bookingId = SaveBooking(departureFlight, returnFlight, fareData);
                        if (bookingId > 0)
                        {
                            HttpContext context = HttpContext.Current;
                            (new Thread(() =>
                            {
                                ////Lưu lại chuyến bay đi
                                //int departureFlightId = SaveFlight(bookingId, departureFlight, false); //false tức là chuyến đi
                                //if (departureFlightId > 0)
                                //{
                                //    //Lưu lại các segment trong chuyến bay
                                //    SaveSegment(departureFlightId, departureFlight);
                                //}

                                ////Lưu lại chuyến bay về nếu có
                                //if (fareData.HasReturn)
                                //{
                                //    int returnFlightId = SaveFlight(bookingId, returnFlight, true); //true tức là chuyến về
                                //    if (returnFlightId > 0)
                                //    {
                                //        //Lưu lại các segment trong chuyến bay
                                //        SaveSegment(returnFlightId, returnFlight);
                                //    }
                                //}

                                //Lưu lại hành khách
                                SavePassengers(bookingId, fareData, context);
                            })).Start();

                            if (fareData.IBE == "galileo")
                            {
                                #region Galileo
                                //Tạo Xml Request
                                PNRBFPrimaryBldChgMods pNRBFPrimaryBldChgMods = GetPNRBFPrimaryBldChgMods(fareData);
                                AirSegSellMods airSegSellMods = GetAirSegSellMods(fareData);
                                EndTransactionMods endTransactionMods = GetEndTransactionMods();
                                string request = "<PNRBFManagement_11>";
                                request += pNRBFPrimaryBldChgMods.GetXml();
                                request += airSegSellMods.GetXml();
                                request += endTransactionMods.GetXml();
                                request += "</PNRBFManagement_11>";

                                //Gửi request, nhận response
                                XmlDocument xmlResponse = new XmlDocument();
                                GalileoConnection conn = new GalileoConnection();
                                try
                                {
                                    //Đặt booking bằng HCM
                                    string hcm_pcc = ConfigurationManager.AppSettings["hcm_pcc_booking"].ToString();
                                    string hcm_name = ConfigurationManager.AppSettings["hcm_name_booking"].ToString();
                                    xmlResponse.LoadXml(conn.SubmitXml(request, "XML", hcm_pcc, hcm_name));
                                }
                                catch
                                {

                                }

                                //Save to Xml files
                                string response = xmlResponse.InnerXml;
                                string appPath = AppDomain.CurrentDomain.BaseDirectory;
                                Common.SaveFile(appPath + "/PNR/" + bookingId.ToString() + "-response.xml", response);
                                Common.SaveFile(appPath + "/PNR/" + bookingId.ToString() + "-request.xml", request);

                                lblAgreeMsg.Visible = false;

                                //Check Booking Success
                                GDSParser parser = new GDSParser();
                                string bookingCode = parser.GetBookingCode(xmlResponse);

                                //Remove FareData Session
                                Session.Remove(Request.QueryString["Search"] + Request.QueryString["SelectedValue"]);
                                Session.Remove(Request.QueryString["Search"] + Request.QueryString[Request.QueryString["SelectedValue"] + "DepartureId"]);
                                Session.Remove(Request.QueryString["Search"] + Request.QueryString[Request.QueryString["SelectedValue"] + "ReturnId"]);

                                if (bookingCode != "")
                                {
                                    //Nếu request đặt chỗ thành công
                                    new BookingDB().UpdateBookingCode(bookingId, bookingCode);
                                    new BookingDB().UpdateBookingStatus(bookingId, "GDSOK"); //GDS OK

                                    Session["FareData" + bookingCode] = fareData;
                                    Session["DepartureFlight" + bookingCode] = departureFlight;
                                    Session["ReturnFlight" + bookingCode] = returnFlight;

                                    Response.Redirect("~/Confirm.aspx?BookingCode=" + bookingCode, false);
                                }
                                else
                                {
                                    //Nếu request đặt chỗ không thành công, tự sinh mã booking
                                    string randomCode = utility.GetRandomForToNumber(5).ToUpper();
                                    new BookingDB().UpdateBookingCode(bookingId, randomCode);
                                    new BookingDB().UpdateBookingStatus(bookingId, "GDSFAIL"); //GDS Fail

                                    //Nếu muốn redirect thẳng sang trang báo đặt chỗ không thành công thì dùng đoạn này
                                    Response.Redirect("~/BookingFailed.aspx", false);
                                }
                                #endregion
                            }
                            else
                            {
                                #region Low cost
                                AirlineServices service = new AirlineServices();
                                //Khai báo tham số cho LCC web service
                                service.AuthenticationValue = new Authentication { Username = "lccservice", Password = "Wfd@!9438DSbvh" };
                                string agentSignOn = "gcornerclub@galileovietnam.com";
                                string agentPassword = "galileo";
                                int itineraryType = !fareData.HasReturn ? 1 : 0; //1 là one way, 0 là round trip
                                string departure = departureFlight.StartPointAirport.Code;
                                string destination = departureFlight.EndPointAirport.Code;
                                string departureDate = fareData.DepartureDate.ToString("dd/MM/yyyy");
                                string returnDate = fareData.ReturnDate.ToString("dd/MM/yyyy");
                                string ADT = fareData.TotalAdult.ToString();
                                string CHD = fareData.TotalChild.ToString();
                                string INF = fareData.TotalInfant.ToString();
                                string departureSelectValue = departureFlight.FlightInfo;
                                string returnSelectValue = returnFlight != null ? returnFlight.FlightInfo : "";

                                List<Passenger> listPassengers = GetListPaxForLcc();
                                Passenger[] arrayPassengers = listPassengers.ToArray();
                                string response = "";
                                string bookingCode = "";
                                if (!fareData.HasReturn)
                                {
                                    //One way
                                    response = service.SubmitConfirmBookingFlexible(agentSignOn, agentPassword, arrayPassengers, fareData.SessionId, "", "", departureFlight.AirlineDetail.Code, departureFlight.AirlineDetail.Code, itineraryType, departure, destination, departureDate, returnDate, ADT, CHD, INF, departureSelectValue, returnSelectValue);
                                }
                                else
                                {
                                    //Round trip
                                    response = service.SubmitConfirmBookingFlexible(agentSignOn, agentPassword, arrayPassengers, "", "", fareData.SessionId, departureFlight.AirlineDetail.Code, departureFlight.AirlineDetail.Code, itineraryType, departure, destination, departureDate, returnDate, ADT, CHD, INF, departureSelectValue, returnSelectValue);
                                }

                                //Remove FareData Session
                                Session.Remove(Request.QueryString["Search"] + Request.QueryString["SelectedValue"]);
                                Session.Remove(Request.QueryString["Search"] + Request.QueryString[Request.QueryString["SelectedValue"] + "DepartureId"]);
                                Session.Remove(Request.QueryString["Search"] + Request.QueryString[Request.QueryString["SelectedValue"] + "ReturnId"]);
                                //Remove LCC Data Session
                                Session.Remove(Request.QueryString["Search"] + "Lcc");

                                if (response != "")
                                {
                                    string[] array = response.Split('|');
                                    if (array.Length > 1)
                                    {
                                        bookingCode = array[1];
                                        if (bookingCode != "")
                                        {
                                            //Nếu request đặt chỗ thành công
                                            new BookingDB().UpdateBookingCode(bookingId, bookingCode);
                                            new BookingDB().UpdateBookingStatus(bookingId, "LCCOK"); //LCC OK

                                            Session["FareData" + bookingCode] = fareData;
                                            Session["DepartureFlight" + bookingCode] = departureFlight;
                                            Session["ReturnFlight" + bookingCode] = returnFlight;

                                            Response.Redirect("~/Confirm.aspx?BookingCode=" + bookingCode, false);
                                        }
                                    }
                                }

                                if (bookingCode == "")
                                {
                                    //Nếu request đặt chỗ không thành công, tự sinh mã booking
                                    string randomCode = utility.GetRandomForToNumber(5).ToUpper();
                                    new BookingDB().UpdateBookingCode(bookingId, randomCode);
                                    new BookingDB().UpdateBookingStatus(bookingId, "LCCFAIL"); //LCC Fail

                                    //Nếu muốn redirect thẳng sang trang báo đặt chỗ không thành công thì dùng đoạn này
                                    Response.Redirect("~/BookingFailed.aspx", false);
                                }

                                #endregion
                            }
                        }
                        else
                        {
                            Response.Redirect("~/BookingFailed.aspx", false);
                        }
                    }
                    else
                    {
                        ckbAccept.Focus();
                        lblAgreeMsg.Visible = true;
                    }
                }
            }
            catch
            {
                Response.Redirect("~/BookingFailed.aspx", false);
            }
        }
    }
}